<?php

namespace apiend\modules\download\models;

use Yii;
use yii\db\Expression;
use common\components\office\grid\SelectColumn;
use common\models\shop\ShopOrder;
use common\models\shop\ShopOrderDeliverGoods;
use common\models\shop\ShopOrderGoods;
use common\models\base\BaseExpress;

/**
 * 待发货订单查询模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class OrderDeliverySearch extends ShopOrderGoods implements DownloadExportInterface {

    use DownloadExportTrait;

    /**
     * @var string 货运方式
     */
    public $freightMode = 2;

    /**
     * @var string 物流公司
     */
    public $express = 0;

    /**
     * @var string 运单号
     */
    public $expressNo;

    /**
     * @var string 查询类型
     */
    public $keytype;

    /**
     * @var string 关键词
     */
    public $keyword;

    /**
     * @var string 时间区间
     */
    public $datetimes;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['keytype', 'keyword', 'datetimes', 'store_id'], 'safe'],
        ];
    }

    /**
     * 绑定过滤条件
     * @param \common\db\ActiveQuery $query
     * @param string $alias
     */
    protected function buildQuery() {
        $query = static::find()->alias('t');
        $query->innerJoinWith('order order');
        $query->joinWith('orderRefund orderRefund');
        $query->andWhere([
            'and',
            ['t.store_id' => $this->store_id],
            ['>=', 'order.status', ShopOrder::STATUS_PAID],
            ['<', 'order.status', ShopOrder::STATUS_SHIPPED],
            ['!=', 'order.trade_id', 0],
            new Expression('order.pay_time >= order.created_at'),
            [
                'or',
                ['orderRefund.id' => null],
                ['>', 'orderRefund.deleted_at', 0],
                ['<', 'orderRefund.status', 0],
            ]
        ]);
        $subQuery = ShopOrderDeliverGoods::find()->select([
            'order_goods_id',
            'nums' => 'SUM(nums)',
        ])->groupBy('order_goods_id');
        $query->leftJoin(['deliverGoods' => $subQuery], 'deliverGoods.order_goods_id = t.id');
        $query->orderBy([
            'order.created_at' => SORT_ASC
        ]);

        $this->bindKeywords($query, 'order');
        if (!empty($this->datetimes)) {
            list($beginDate, $endDate) = $this->datetimes;
            $query->andFilterDuration('order.created_at', Yii::$app->formatter->asTimestamp($beginDate), Yii::$app->formatter->asTimestamp($endDate));
        }

        $query->debug();
        return $query;
    }

    /**
     * 全部订单
     * @param \common\db\ActiveQuery $query
     */
    protected function bindKeywords($query, $alias = 't') {
        $word = trim($this->keyword);
        if (!$word) {
            return;
        }
        $condition = [
            'or',
        ];
        if ($this->keytype == 'order_no') {
            $condition[] = [$alias . 'order_no' => $word];
        } elseif ($this->keytype == 'user_id') {
            $condition[] = [$alias . 'user_id' => $word];
        } elseif ($this->keytype == 'receiver') {
            $query->joinWith('address address');
            $condition[] = ['like', 'address.name', $word];
        } elseif ($this->keytype == 'receiver_mobile') {
            $query->joinWith('address address');
            $condition[] = ['like', 'address.mobile', $word];
        } elseif ($this->keytype == 'goods_name') {
            $condition[] = ['like', 't.name', $word];
            $condition[] = ['like', 't.goods_name', $word];
        } else {
            $query->joinWith('address address');
            if (StringHelper::isNumber($word)) {
                $condition[] = [$alias . 'user_id' => $word];
                $condition[] = [$alias . 'order_no' => $word];
                if (StringHelper::isMobile($word)) {
                    $condition[] = ['address.mobile' => $word];
                }
            } else {
                $condition = [
                    'or',
                    ['like', 't.name', $word],
                    ['like', 't.goods_name', $word],
                    ['like', 'address.name', $word],
                ];
            }
        }
        $query->andWhere($condition);
    }

    /**
     * 生成下载文件的名称
     * @return string
     */
    public function exportTitle() {
        return Yii::t('message', '{time}{name}', [
            'time' => date('Y年m月d日H:i:s'),
            'name' => '前待发货订单',
        ]);
    }

    /**
     * 生成下载文件的名称
     * @return string
     */
    public function exportFileName($ext = true) {
        return Yii::t('message', '{time}-{title}{ext}', [
            'time' => date('Y年m月d日'),
            'title' => '待发货订单',
            'ext' => $ext ? '.xlsx' : '',
        ]);
    }

    public function exportCaptionOptions() {
        return [
            [
                'text' => '报表生成时间：' . date('Y-m-d H:i:s'),
                'styles' => [
                    'alignment' => [
                        'horizontal' => 'center',
                        'vertical' => 'center',
                        'wrapText' => true,
                    ],
                ],
            ],
            [
                'text' => '店铺：' . $this->store->name,
                'styles' => [
                    'alignment' => [
                        'horizontal' => 'center',
                        'vertical' => 'center',
                        'wrapText' => true,
                    ],
                ],
            ],
            [
                'height' => 100,
                'text' => '相关说明：以下内容格式请勿变动，批量发货将严格校验文件内容格式，因数据格式变动可能造成物流信息上传失败。特别提醒，批量发货支持按订单或商品进行拆分发货，不支持按数量进行拆分发货，如需按商品件数拆分，请使用商品发货功能进行拆分发货。',
                'styles' => [
                    'font' => [
                        'color' => [
                            'rgb' => 'ff2200'
                        ]
                    ],
                    'alignment' => [
                        'horizontal' => 'center',
                        'vertical' => 'center',
                        'wrapText' => true,
                    ]
                ],
            ],
        ];
    }

    /**
     * 获取发货方式
     * @return string
     */
    public function getFreightModeList() {
        return [
            '普通快递',
            '无需物流',
            '暂不发货',
        ];
    }

    /**
     * 获取快递公司列表
     * @return string
     */
    public function getExpressList() {
        $expressList = BaseExpress::findByList();
        $data = ['-其他-'];
        foreach ($expressList as $express) {
            $data[] = implode('_', [
                $express->code,
                $express->name
            ]);
        }
        return $data;
    }

    /**
     * @inheritdoc
     */
    public function exportFields() {
        return [
            [
                'attribute' => 'order.order_no',
                'unlock' => false,
                'borderSeparation' => true,
                'headerOptions' => [
                    'width' => 30,
                    'alignment' => [
                        'horizontal' => 'center',
                    ],
                    'font' => [
                        'bold' => true,
                    ],
                ],
//                'contentOptions' => [
//                    'quotePrefix' => true,
//                ],
            ],
            [
                'attribute' => 'goods_id',
                'label' => '商品SKUID',
                'format' => 'integer',
                'unlock' => false,
                'headerOptions' => [
                    'width' => 12,
                    'alignment' => [
                        'horizontal' => 'center',
                    ],
                    'font' => [
                        'bold' => true,
                    ],
                ],
//                'contentOptions' => [
//                    'quotePrefix' => true,
//                ],
            ],
            [
                'attribute' => 'title',
                'label' => '订单商品',
                'unlock' => false,
                'headerOptions' => [
                    'width' => 30,
                    'alignment' => [
                        'horizontal' => 'center',
                    ],
                    'font' => [
                        'bold' => true,
                    ],
                ],
            ],
            [
                'attribute' => 'goods_number',
                'label' => '商品数量',
                'unlock' => false,
                'headerOptions' => [
                    'width' => 12,
                    'alignment' => [
                        'horizontal' => 'center',
                    ],
                    'font' => [
                        'bold' => true,
                    ],
                ],
                'contentOptions' => [
                    'alignment' => [
                        'horizontal' => 'right',
                    ],
                ],
            ],
            [
                'class' => SelectColumn::class,
                'dropdownList' => $this->getFreightModeList(),
                'attribute' => 'freightMode',
                'label' => '发货方式',
                'headerOptions' => [
                    'width' => 20,
                    'alignment' => [
                        'horizontal' => 'center',
                    ],
                    'font' => [
                        'bold' => true,
                    ],
                ],
                'contentOptions' => [
                    'alignment' => [
                        'horizontal' => 'center',
                    ],
                ],
            ],
            [
                'class' => SelectColumn::class,
                'dropdownList' => $this->getExpressList(),
                'attribute' => 'express',
                'label' => '物流公司名称',
                'headerOptions' => [
                    'width' => 20,
                    'alignment' => [
                        'horizontal' => 'center',
                    ],
                    'font' => [
                        'bold' => true,
                    ],
                ],
                'contentOptions' => [
                    'alignment' => [
                        'horizontal' => 'center',
                    ],
                ],
            ],
            [
                'attribute' => 'expressNo',
                'label' => '物流单号（普通快递时必须设置单号）',
                'headerOptions' => [
                    'width' => 30,
                    'alignment' => [
                        'horizontal' => 'center',
                    ],
                    'font' => [
                        'bold' => true,
                    ],
                ],
            ],
        ];
    }

}
